import {
  ErrorRequestHandler,
  Request,
  Response,
  NextFunction,
  response,
} from "express";
import { err as aaa, err } from "./infoerr";
import { reg } from "../../type";
import md5 from "md5";
import { userinfo, type asyncPromise } from "../../interface";

//登录验证

const name: reg = /^[A-Za-z][A-Za-z0-9]{2,9}$/;
const pwd: reg = /^[A-Za-z0-9_+-.]{6,16}$/;

const isNum: reg = /^[1-9]{1,4}$/;
export default {
  user(req: Request, res: Response, next: NextFunction) {
    if (!req.body || !req.body.name) return err(res, "请填写账号");
    if (!req.body || !req.body.pwd) return err(res, "请填写密码");
    if (name.test(req.body.name) && pwd.test(req.body.pwd)) {
      const body: userinfo = {
        name: req.body.name,
        pwd: req.body.pwd,
        nickName: req.body.nickName ? req.body.nickName : null,
        imgUrl: req.body.imgUrl ? req.body.imgUrl : null,
      };
      body.pwd = md5(body.pwd);
      req.body = body;
      return next();
    }
    return err(res, "账号或者密码不符合规范", {
      账号: "字母开头3-9位不能包含除了_以外的字符",
      密码: "由A-Z0-9_+-.组成6-16位",
    });
  },
  limit(req: Request, res: Response, next: NextFunction) {
    if (!req.query || !req.query.x || !req.query.y) err(res, "没有参数");
    if (isNum.test(req.query.x as string) && isNum.test(req.query.y as string))
      return next();

    return err(res, "参数错误", { reg: "/^[1-9]{1,4}$/" });
  },
  top(req: Request, res: Response, next: NextFunction) {
    if (!req.query || !req.query.x || !req.query.y || !req.query.z)
      return err(res, "参数数量错误");
    const { x, y, z } = req.query;
    if (Object.is(+x, NaN) || Object.is(+y, NaN) || Object.is(+z, NaN))
      return err(res, "参数类型错误", { x: "number", y: "number" });
    next();
  },
};
